import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { 
  Card, Tree, Col, Row, Button, notification, Popconfirm, 
  Modal, Input, Spin, Pagination, Empty, Tooltip 
} from "antd";
import { 
  DeleteOutlined, PlusCircleOutlined, EditOutlined 
} from '@ant-design/icons';
import useStore from '../../components/useStore';
import store from '../../untils/store';
import request from '../../untils/request';

// 常量定义
const PAGE_SIZE = 10;
const ROOT_NODE_ID = 1;
const MIN_TITLE_LENGTH = 2;
const TREE_NODE_MAX_WIDTH = 'calc(100% - 32px)';
const TREE_CARD_FIXED_WIDTH = 280;
const TREE_CARD_COLLAPSED_WIDTH = 220;

const Framework = () => {
  // 状态管理
  const { user } = store();
  const { collapsed } = useStore();
  
  // 组织架构相关状态
  const [frameworkData, setFrameworkData] = useState([]);
  const [selectedFrameworkIds, setSelectedFrameworkIds] = useState([]);
  const [currentFrameworkId, setCurrentFrameworkId] = useState(ROOT_NODE_ID);
  const [hasSelected, setHasSelected] = useState(true);
  const [frameworkInfo, setFrameworkInfo] = useState({
    id: null,
    title: "",
    total: 0,
    data: []
  });
  
  // 其他状态
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [newFramework, setNewFramework] = useState({ title: "" });
  const [editedFramework, setEditedFramework] = useState({ title: "", id: null });
  const [currentPage, setCurrentPage] = useState(1);
  const [totalEmployees, setTotalEmployees] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [hasHistoryData, setHasHistoryData] = useState(false);

  // 计算树卡片宽度
  const getTreeCardWidth = () => {
    return collapsed ? TREE_CARD_COLLAPSED_WIDTH : TREE_CARD_FIXED_WIDTH;
  };

  // 格式化组织架构数据 - 优化树形结构文本对齐
  const formattedFrameworkData = useMemo(() => {
    const formatNode = (nodes) => {
      return nodes.map(node => {
        const titleWithTooltip = (
          <Tooltip title={node.title} placement="right" mouseEnterDelay={0.3}>
            <span style={styles.treeNodeText}>{node.title}</span>
          </Tooltip>
        );
        
        return {
          ...node,
          title: titleWithTooltip,
          children: node.children ? formatNode(node.children) : null
        };
      });
    };
    
    return formatNode(frameworkData);
  }, [frameworkData]);

  // 监听数据变化，更新历史数据标记
  useEffect(() => {
    setHasHistoryData(frameworkInfo.data && frameworkInfo.data.length > 0);
  }, [frameworkInfo.data]);

  // 获取组织架构数据
  const fetchFrameworkData = useCallback(() => {
    request("/admin/framework/getFramework", {
      mode: 'cors'
    })
    .then(data => setFrameworkData(data))
    .catch(error => {
      notification.error({ message: "获取组织架构失败", description: error.message });
    });
  }, []);

  // 初始加载组织架构
  useEffect(() => {
    fetchFrameworkData();
  }, [fetchFrameworkData]);

  // 处理组织架构多选
  const handleFrameworkCheck = useCallback((checkedIds) => {
    setSelectedFrameworkIds(checkedIds);
  }, []);

  // 处理组织架构单选
  const handleFrameworkSelect = useCallback((selectedId) => {
    const newId = selectedId[0] || 0;
    setCurrentFrameworkId(newId);
    
    if (newId !== 0) {
      setHasSelected(true);
      setCurrentPage(1);
      fetchFrameworkInfo();
    } else {
      setHasSelected(false);
    }
  }, []);

  // 获取部门详情及成员
  const fetchFrameworkInfo = useCallback(() => {
    if (currentFrameworkId === 0) return;

    setIsLoading(true);
    
    request("/admin/framework/getFrameworkInfoById", {
      method: 'POST',
      mode: 'cors',
      body: {
        frameworkId: currentFrameworkId,
        pageSize: PAGE_SIZE,
        offset: (currentPage - 1) * PAGE_SIZE
      }
    })
    .then(data => {
      setFrameworkInfo(data);
      setTotalEmployees(data.total);
      setIsLoading(false);
    })
    .catch(error => {
      notification.error({ message: "获取详情失败", description: error.message });
      setIsLoading(false);
    });
  }, [currentFrameworkId, currentPage]);

  // 页面加载时初始化第一个组织的数据
  useEffect(() => {
    if (frameworkData.length > 0 && currentFrameworkId === ROOT_NODE_ID) {
      fetchFrameworkInfo();
    }
  }, [frameworkData, currentFrameworkId, fetchFrameworkInfo]);

  // 分页变化时查询
  useEffect(() => {
    if (hasSelected) {
      fetchFrameworkInfo();
    }
  }, [currentPage, hasSelected, fetchFrameworkInfo]);

  // 新增组织架构
  const handleAddFramework = useCallback(() => {
    if (currentFrameworkId === 0) {
      notification.warning({ message: "请先选择上级组织" });
      return;
    }

    if (!newFramework.title || newFramework.title.length < MIN_TITLE_LENGTH) {
      notification.warning({ message: `架构名称不能少于${MIN_TITLE_LENGTH}个字符` });
      return;
    }

    request("/admin/framework/addFramework", {
      method: 'POST',
      mode: 'cors',
      body: {
        newFramework: { ...newFramework, parent_framework_id: currentFrameworkId }
      }
    })
    .then(data => {
      if (data.code === 200) {
        notification.success({ message: data.msg });
        fetchFrameworkData();
        setIsAddModalVisible(false);
      } else {
        notification.error({ message: data.msg });
      }
    })
    .catch(error => {
      notification.error({ message: "操作失败", description: error.message });
    });
  }, [currentFrameworkId, newFramework, user, fetchFrameworkData]);

  // 删除选中的组织架构
  const handleDeleteFramework = useCallback(() => {
    if (selectedFrameworkIds.length === 0) {
      notification.warning({ message: "请先选择要删除的架构" });
      return;
    }

    if (selectedFrameworkIds.includes(ROOT_NODE_ID)) {
      notification.error({ message: "根节点不允许删除" });
      return;
    }

    request("/admin/framework/deleteFramework", {
      method: 'POST',
      mode: 'cors',
      body: {
        frameworkIds: selectedFrameworkIds
      }
    })
    .then(data => {
      if (data.code === 200) {
        notification.success({ message: data.msg });
        setSelectedFrameworkIds([]);
        fetchFrameworkData();
      } else {
        notification.error({ message: data.msg });
      }
    })
    .catch(error => {
      notification.error({ message: "操作失败", description: error.message });
    });
  }, [selectedFrameworkIds, user, fetchFrameworkData]);

  // 编辑相关方法
  const handleEditModalOpen = useCallback(() => {
    if (currentFrameworkId === 0) {
      notification.warning({ message: "请选择公司/部门进行编辑" });
      return;
    }
    setEditedFramework({
      title: frameworkInfo.title,
      id: frameworkInfo.id
    });
    setIsEditModalVisible(true);
  }, [frameworkInfo, currentFrameworkId]);

  const handleSaveEditedFramework = useCallback(() => {
    if (!editedFramework.title || editedFramework.title.length < MIN_TITLE_LENGTH) {
      notification.warning({ message: `架构名称不能少于${MIN_TITLE_LENGTH}个字符` });
      return;
    }

    request("/admin/framework/editFramework", {
      method: 'POST',
      mode: 'cors',
      body: {
        newEditFramework: editedFramework
      }
    })
    .then(data => {
      if (data.code === 200) {
        notification.success({ message: data.msg });
        fetchFrameworkData();
        fetchFrameworkInfo();
        setIsEditModalVisible(false);
      } else {
        notification.error({ message: data.msg });
      }
    })
    .catch(error => {
      notification.error({ message: "操作失败", description: error.message });
    });
  }, [editedFramework, user, fetchFrameworkData, fetchFrameworkInfo]);

  // 渲染员工列表项
  const renderEmployeeItem = (item, index) => {
    const isEvenRow = index % 2 === 0;
    return (
      <Row
        key={index}
        style={{
          width: "100%",
          marginTop: "0.5vh",
          marginLeft: "0.25vw",
          borderBottom: "1px solid #e8e8e8",
          padding: "0.1rem",
          backgroundColor: isEvenRow ? "#f9fafb" : "#ffffff",
          transition: "background-color 0.2s"
        }}
        onMouseEnter={(e) => e.currentTarget.style.backgroundColor = "#f3f4f6"}
        onMouseLeave={(e) => e.currentTarget.style.backgroundColor = isEvenRow ? "#f9fafb" : "#ffffff"}
        gutter={24}
      >
        <Col span={3}>{index + 1}</Col>
        <Col span={7} style={styles.employeeCell}>
          <Tooltip title={item.name}>{item.name}</Tooltip>
        </Col>
        <Col span={7} style={styles.employeeCell}>
          <Tooltip title={item.work_number}>{item.work_number}</Tooltip>
        </Col>
        <Col span={7} style={styles.employeeCell}>
          <Tooltip title={item.position}>{item.position}</Tooltip>
        </Col>
      </Row>
    );
  };

  return (
    <div style={{...styles.mainContainer, width: collapsed ? "94%" : "calc(100% - 300px)"}}>
      <div style={styles.container}>
        <div style={styles.contentWrapper}>
          {/* 左侧组织架构树 */}
          <Card 
            hoverable 
            title="公司架构" 
            style={{
              ...styles.treeCard,
              width: getTreeCardWidth()
            }}
          >
            <Tree
              treeData={formattedFrameworkData}
              blockNode
              defaultExpandAll
              checkable
              onCheck={handleFrameworkCheck}
              onSelect={handleFrameworkSelect}
              selectedKeys={[currentFrameworkId]}
              style={styles.treeContainer}
              // 优化树形结构对齐的关键属性
              showLine={false}
              indentSize={16}
            />
          </Card>

          {/* 右侧操作和详情区域 */}
          <Card 
            hoverable 
            style={styles.detailsCard}
            title={
              <Row gutter={16} align="middle" justify="flex-start">
                {/* 新增按钮 */}
                <Col>
                  <Button 
                    onClick={() => setIsAddModalVisible(true)} 
                    icon={<PlusCircleOutlined />} 
                    type="primary"
                    style={styles.addButton}
                  >
                    新增
                  </Button>
                </Col>
                {/* 删除按钮 - 改为红色 */}
                <Col>
                  <Popconfirm
                    title="误删警告，请确认您所要删除的组织架构！（删除后，归属于该组织架构的人员将被划分为空归属）"
                    onConfirm={handleDeleteFramework}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button 
                      icon={<DeleteOutlined />} 
                      style={styles.deleteButton}
                    >
                      删除所选
                    </Button>
                  </Popconfirm>
                </Col>
              </Row>
            }
          >
            {/* 部门信息 */}
            <div style={styles.departmentInfo}>
              <span>当前部门：</span>
              <Tooltip title={frameworkInfo.title} style={{ marginRight: 8 }}>
                <span style={styles.departmentName}>{frameworkInfo.title || (hasHistoryData ? "（已取消选择）" : "")}</span>
              </Tooltip>
              {hasSelected && (
                <Button 
                  onClick={handleEditModalOpen} 
                  size='small' 
                  icon={<EditOutlined />}
                >
                  编辑
                </Button>
              )}
            </div>

            {/* 员工列表表头 */}
            <Row style={styles.tableHeader} gutter={24}>
              <Col span={3}>序号</Col>
              <Col span={7}>姓名</Col>
              <Col span={7}>工号</Col>
              <Col span={7}>职务</Col>
            </Row>

            {/* 员工列表内容 */}
            {isLoading ? (
              <div style={styles.loadingIndicator}>
                <Spin size="large" />
              </div>
            ) : (
              <>
                <div style={styles.contentContainer}>
                  {hasHistoryData && frameworkInfo.data.map((item, index) => 
                    renderEmployeeItem(item, index)
                  )}
                  
                  {!hasHistoryData && hasSelected && (
                    <Empty description="当前组织没有直接下属" />
                  )}
                  
                  {!hasHistoryData && !hasSelected && (
                    <Empty description="请选择一个组织架构查看详情" />
                  )}
                </div>
                
                {hasSelected && hasHistoryData && (
                  <Pagination 
                    current={currentPage}
                    onChange={setCurrentPage}
                    total={totalEmployees}
                    pageSize={PAGE_SIZE}
                    hideOnSinglePage
                    style={styles.pagination}
                  />
                )}
              </>
            )}
          </Card>

          {/* 新增组织架构模态框 */}
          <Modal
            title="新增组织架构"
            open={isAddModalVisible}
            onCancel={() => setIsAddModalVisible(false)}
            onOk={handleAddFramework}
          >
            <p>架构名称</p>
            <Input 
              onChange={(e) => setNewFramework(prev => ({ ...prev, title: e.target.value }))} 
              value={newFramework.title} 
              placeholder='请输入组织架构名称' 
              maxLength={100} 
              showCount
            />
          </Modal>

          {/* 编辑部门模态框 */}
          <Modal
            title="编辑部门"
            open={isEditModalVisible}
            onCancel={() => setIsEditModalVisible(false)}
            onOk={handleSaveEditedFramework}
          >
            <p>架构名称</p>
            <Input 
              onChange={(e) => setEditedFramework(prev => ({ ...prev, title: e.target.value }))} 
              value={editedFramework.title} 
              placeholder='请输入新的组织架构名称' 
              maxLength={100} 
              showCount
            />
          </Modal>
        </div>
      </div>
    </div>
  );
};

// 样式定义 - 新增和调整的样式
const styles = {
  // 其他样式保持不变...
  mainContainer: {
    height: "94%",
    backgroundColor: "#F1F1F1",
    right: "1%",
    top: "4vh",
    overflow: "hidden",
    backgroundSize: "100% 100%",
    position: "absolute",
    color: "white",
    fontSize: "0.8rem",
    transition: "width 0.3s ease"
  },
  container: {
    width: "98%",
    height: "95%",
    position: "absolute",
    top: "3%",
    left: "1%",
    backgroundColor: "white",
    color: "black",
    borderRadius: "10px",
  },
  contentWrapper: {
    fontSize: "0.7rem",
    position: "relative",
    width: "96%",
    marginLeft: "2%",
    backgroundColor: "",
    display: "flex",
    textIndent: "1rem",
    justifyContent: "flex-start",
    alignContent: "flex-start",
    flexWrap: "wrap"
  },
  treeCard: {
    height: "80vh",
    overflow: "auto",
    marginTop: "2vh",
    transition: "width 0.3s ease"
  },
  detailsCard: {
    marginTop: "2vh",
    marginLeft: "2vw",
    flex: 1,
    minWidth: 500,
    transition: "width 0.3s ease"
  },
  // 树形结构样式优化
  treeContainer: {
    padding: "0",
    textAlign: "left",
  },
  treeNodeText: {
    display: "inline-block",
    maxWidth: TREE_NODE_MAX_WIDTH,
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    verticalAlign: "middle",
    textAlign: "left",
    paddingLeft: "2px", // 减少左内边距使文本更靠左
  },
  // 按钮样式调整
  addButton: {
    marginRight: 8,
  },
  deleteButton: {
    backgroundColor: "#f5222d",
    borderColor: "#f5222d",
    color: "#fff",
    '&:hover': {
      backgroundColor: "#cf1322",
      borderColor: "#cf1322",
    },
  },
  // 其他样式保持不变...
  departmentInfo: {
    marginBottom: 16,
    fontSize: "1rem",
    display: "flex",
    alignItems: "center"
  },
  departmentName: {
    maxWidth: "300px",
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    textAlign: "left"
  },
  tableHeader: {
    width: "100%",
    marginTop: '0.5vh',
    marginLeft: "0.25vw",
    backgroundColor: '#156ef3d8',
    color: 'white',
    padding: "0.3rem 0"
  },
  loadingIndicator: {
    textAlign: "center",
    padding: "50px 0",
    height: "40vh",
    display: "flex",
    alignItems: "center",
    justifyContent: "center"
  },
  contentContainer: {
    height: "40vh",
    overflowY: "auto",
    overflowX: "hidden",
    padding: "0 10px",
    width: "100%"
  },
  pagination: {
    marginTop: 16,
    textAlign: "right"
  },
  employeeCell: {
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    textAlign: "left"
  }
};

export default Framework;
